<!-- 仓库报表   库存库龄查询-成品 -->

<template>
  <basic-container>
    <el-tabs type="border-card" class="tab-font">
      <el-tab-pane label="搜索"> </el-tab-pane>
      <avue-form ref="form" :option="option" v-model="form">
        <template slot="btn">
          <el-button type="primary" size="small" class="el-icon-search" :disabled="btnDisabled" @click="handleSubmit">搜索</el-button>
          <el-button size="small" class="el-icon-delete" :disabled="btnDisabled" @click="handleCancel">清空</el-button>
        </template>
      </avue-form>
    </el-tabs>
    <el-tabs type="border-card" class="chart-tab tab-font" v-model="activeName" @tab-click="handleClick" v-loading="echartLoading">
      <el-tab-pane label="明细" name="detail"> </el-tab-pane>
      <el-tab-pane label="趋势" name="trend"> </el-tab-pane>
      <el-row :gutter="20">
        <div v-if="activeName === 'detail'">
          <el-col :span="12">
            <chart-view class="chart-content" :chart-option="barOption" @click="handleOnClick" :auto-resize="true" width="100%" height="450px" />
          </el-col>
          <el-col :span="12">
            <chart-view class="chart-content" :chart-option="peiOption" @click="handleOnClick" :auto-resize="true" width="100%" height="450px" />
          </el-col>
        </div>
        <div v-if="activeName === 'trend'">
          <chart-view class="chart-content" :chart-option="lineOption" :auto-resize="true" width="100%" height="450px" />
        </div>
      </el-row>
      <avue-crud
        v-if="activeName === 'detail'"
        :option="tableOption"
        :table-loading="loading"
        :data="data"
        :summary-method="summaryMethod"
        :page="tablePage"
        @current-change="currentChange"
        @size-change="sizeChange"
        ref="crud"
      >
        <template slot="menu" slot-scope="{ type, size, row, index }">
          <el-button icon="el-icon-view" :size="size" type="text" @click="handleViewDetail(row)">详情</el-button>
        </template>
        <template slot="menuLeft">
          <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出 </el-button>
        </template>
        <template slot="menuRight">
          <span>当前查询时间: {{ this.nowDate }}</span>
        </template>
      </avue-crud>
      <avue-crud class="trend-crud" v-if="activeName === 'trend'" ref="trendCrud" :option="trendTableOption" :table-loading="echartLoading" :data="data">
        <template slot="statisticalMonthHeader" slot-scope="{ column }">
          <div class="custom-header">
            <div class="right">库龄</div>
            <div class="left">日期</div>
          </div>
        </template>
        <template slot="menuLeft">
          <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出 </el-button>
        </template>
      </avue-crud>
    </el-tabs>
    <el-dialog title="详 情" append-to-body :visible.sync="dialogVisible" width="60%" :destroy-on-close="true">
      <el-row :gutter="20">
        <el-col :span="4" :offset="2">产品编码:{{ forminfo.productPartNo || '--' }} </el-col>
        <el-col :span="4">产品名称:{{ forminfo.productPartName || '--' }} </el-col>
        <el-col :span="4">产品型号:{{ forminfo.productPartModel || '--' }} </el-col>
        <!-- <el-col :span="4">客户:{{ forminfo.vendorName || '--' }} </el-col> -->
      </el-row>
      <avue-crud :option="detailTableOption" :data="detailData" ref="crud"> </avue-crud>
    </el-dialog>
    <el-dialog title="查询进度" :visible.sync="progressVisible" width="30%" append-to-body>
      <el-progress :percentage="currentProgress" stroke-width="40" stroke-linecap="square" :show-text="false"> </el-progress>
    </el-dialog>
    <export-comp ref="exportComp" :page-api-url="pageApiUrl" :option="exportOption" :page="activeName === 'detail' ? tablePage : {}" :query="exportParams" :file-name="fileName">
    </export-comp>
  </basic-container>
</template>

<script>
import { option, tableOption, peiOption, barOption, lineOption, detailTableOption, trendTableOption } from '@/views/report/InventoryFinishedProduct';
import ChartView from '@/components/chart/index.vue';
import { getDetailList, getTableList, getChartData, getShapeData } from '@/api/report/InventoryFinishedProduct';
import { filterEmptyValues } from '@/util/util';
import exportComp from '@/components/export-comp';
import moment from 'moment';
export default {
  name: 'InventoryFinishedProduct',
  components: {
    ChartView,
    exportComp
  },
  data() {
    return {
      exportParams: {},
      echartLoading: false,
      dialogVisible: false,
      progressVisible: false,
      intervalId: null,
      currentProgress: 0,
      nowDate: moment(new Date()).format('YYYY年MM月DD日'),
      option,
      form: {},
      forminfo: {},
      tableOption, //明细表
      trendTableOption, // 趋势表
      peiOption,
      barOption,
      lineOption,
      loading: false,
      btnDisabled: false,
      activeName: 'detail',
      data: [],
      tablePage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailTableOption,
      detailData: []
    };
  },
  computed: {
    fileName() {
      return `成品库龄分析-${this.activeName === 'trend' ? '趋势' : '明细'}`;
    },
    pageApiUrl() {
      return this.activeName === 'trend' ? 'mes-warehouse/stat-storage-age-finished/month-list' : 'mes-warehouse/stat-storage-age-finished/page';
    },
    exportOption() {
      return this.activeName === 'trend' ? this.trendTableOption : this.tableOption;
    }
  },
  mounted() {
    // this.onLoad(1);
    // this.getChartData();
    this.getShapeData();
  },
  methods: {
    sizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      this.onLoad();
    },
    currentChange(currentPage) {
      this.tablePage.currentPage = currentPage;
      this.onLoad();
    },
    handleSubmit() {
      this.nowDate = moment(new Date()).format('YYYY年MM月DD日');
      // this.currentProgress = 0;
      // this.progressVisible = true;
      // this.onLoad(1);
      this.getShapeData();
    },
    handleCancel() {
      this.$refs.form.resetForm();
      this.form.storageAgeType = 1;
      // this.onLoad(1);
      this.data = [];
      this.getShapeData();
    },
    async handleClick() {
      const warehouseId = this.findObject(this.option.column, 'warehouseId');
      const productPrtNo = this.findObject(this.option.column, 'productPrtNo');
      this.data = [];
      this.$set(this.form, 'warehouseId', '');
      this.$set(this.form, 'productPartNo', '');
      if (this.activeName === 'detail') {
        warehouseId.disabled = false;
        productPrtNo.disabled = false;
        this.btnDisabled = false;
        this.tablePage.currentPage = 1;
        // this.onLoad(1);
        await this.getShapeData();
      } else {
        warehouseId.disabled = true;
        productPrtNo.disabled = true;
        this.btnDisabled = true;
        this.$nextTick(() => {
          this.getChartData();
        });
      }
    },
    async handleViewDetail(row) {
      const { partMasterId = '', productPartNo = '' } = row;
      this.forminfo = row;
      try {
        const res = await getDetailList({ productPartNo, storageAgeType: this.form.storageAgeType });
        this.detailData = res.data.data;
      } catch (e) {
        console.warn(e);
        this.detailData = [];
      } finally {
        this.dialogVisible = true;
      }
    },
    async getShapeData() {
      let data = {};
      try {
        this.echartLoading = true;

        const params = filterEmptyValues(this.form);
        if (params.$warehouseId) {
          delete params.$warehouseId;
        }
        delete params.storageAgeType;
        const res = await getShapeData(Object.assign(params));
        data = res.data.data;
      } catch (e) {
        data = {};
        // this.data = [];
      } finally {
        this.setChartOption(data);
        this.echartLoading = false;
      }
    },
    async getChartData() {
      let data = [];
      try {
        this.echartLoading = true;
        const params = filterEmptyValues({});
        //getDataOfLastMonths trend 需要传true
        const res = await getChartData(Object.assign(params));
        data = res.data.data;
        if (this.activeName === 'trend') {
          this.data = res.data.data || [];
        }
      } catch (e) {
        data = [];
        this.data = [];
      } finally {
        this.setChartOption(data);
        this.echartLoading = false;
      }
    },
    handleOnClick(params) {
      if (params.seriesType === 'bar' || params.seriesType === 'pie') {
        switch (params.name) {
          case '0-30天':
            this.form.storageAgeType = 1;
            this.onLoad(1);
            break;
          case '31-90天':
            this.form.storageAgeType = 2;
            this.onLoad(1);
            break;
          case '91-180天':
            this.form.storageAgeType = 3;
            this.onLoad(1);
            break;
          case '181-365天':
            this.form.storageAgeType = 4;
            this.onLoad(1);
            break;
          case '365天以上':
            this.form.storageAgeType = 5;
            this.onLoad(1);
            break;
          default:
            break;
        }
      }
    },
    setChartOption(data) {
      if (this.activeName === 'detail') {
        const obj = data || {};
        const quantityData = [obj.quantity0To30, obj.quantity31To90, obj.quantity91To180, obj.quantity181To365, obj.quantityAbove365];
        const priceData = [obj.price0To30, obj.price31To90, obj.price91To180, obj.price181To365, obj.priceAbove365];
        const barData = [
          { value: obj.quantity0To30, name: '0-30天' },
          { value: obj.quantity31To90, name: '31-90天' },
          { value: obj.quantity91To180, name: '91-180天' },
          { value: obj.quantity181To365, name: '181-365天' },
          { value: obj.quantityAbove365, name: '365天以上' }
        ];
        this.$set(this.barOption.series[0], 'data', quantityData);
        // this.$set(this.barOption.series[1], 'data', priceData);
        this.$set(this.peiOption.series[0], 'data', barData);
      } else {
        const xData = data.map((i) => i.statisticalMonth);
        const series = this._cloneDeep(this.lineOption.series);
        data.forEach((i) => {
          series[0].data.push(i.quantity0To30);
          series[1].data.push(i.quantity31To90);
          series[2].data.push(i.quantity91To180);
          series[3].data.push(i.quantity181To365);
          series[4].data.push(i.quantityAbove365);
        });
        this.$set(this.lineOption.xAxis, 'data', xData);
        this.$set(this.lineOption, 'series', series);
      }
    },
    startProgress(data, seconds = 500) {
      const time = seconds < 500 ? 500 : seconds;
      const setInterTime = time / 10;
      this.intervalId = setInterval(() => {
        if (this.currentProgress < 100) {
          this.currentProgress += 10;
        } else {
          clearInterval(this.intervalId);
          this.progressVisible = false;
          this.data = data;
        }
      }, setInterTime);
    },
    async onLoad(page) {
      const startTime = new Date().getTime();
      let endTime;
      let data;
      const pageParams = {
        current: page || this.tablePage.currentPage,
        size: this.tablePage.pageSize,
        storageAgeType: this.form.storageAgeType || 1
      };
      const searchParams = filterEmptyValues(this.form);
      if (searchParams.$warehouseId) {
        delete searchParams.$warehouseId;
      }
      try {
        const res = await getTableList(Object.assign(searchParams, pageParams));
        data = (res.data.data || {}).records;
        this.tablePage.total = res.data.data.total;
        this.endTime = new Date().getTime();
      } catch (e) {
        endTime = new Date().getTime();
        this.setChartOption([]);
        data = [];
      }
      const seconds = endTime - startTime;
      this.startProgress(data, seconds);
    },
    handleExport() {
      this.exportParams = Object.assign(filterEmptyValues(this.form));
      this.$refs.exportComp.visible = true;
    },
    summaryMethod({ columns, data }) {
      const sums = [];
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          let prop = column.property;
          if (['quantity', 'price'].includes(prop)) {
            let values = this.data.map((item) => Number(item[prop] || 0));
            let all =
              values.length !== 0
                ? (sums[index] = values.reduce((a, b) => {
                    return a + b;
                  }))
                : 0;

            sums[index] = all;
            if (prop === 'price') {
              sums[index] = `￥${all.toFixed(4)}`;
            }
          } else if (prop === 'productPartNo') {
            sums[index] = '合计';
          } else {
            sums[index] = '';
          }
        });
      }
      return sums;
    }
  }
};
</script>

<style scoped lang="scss">
.chart-tab {
  margin-top: 24px;
  height: calc(100vh - 350px);
  overflow-y: scroll;
}
.left {
  text-align: left;
  position: relative;
  padding-left: 10px;
}

.left::after {
  content: '';
  width: 100%;
  height: 0px;
  position: absolute;
  border-bottom: 1px solid black;
  top: 0;
  left: 0;
  transform: rotate(12deg);
}

.right {
  text-align: right;
  padding-right: 10px;
}

.trend-crud {
  ::v-deep .avue-crud__pagination {
    display: none;
  }
}
</style>
